package sz.szsmk.citizencard.widget;
 
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import sz.szsmk.citizencard.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chensf on 17/10/4.
 */

public class CitzenCardTextView extends View {

    private String mText = "";

    private Paint mPaint;
    private float mGapWidth;
    private int mSplitTextNumber ;


    public void setText(String text){
        this.mText = text;
    }

    public CitzenCardTextView(Context context) {
        this(context,null);
    }

    public CitzenCardTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public CitzenCardTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureWidth(widthMeasureSpec),
                measureHeight(heightMeasureSpec));
    }

    /**
     * Determines the width of this view
     * @param measureSpec A measureSpec packed into an int
     * @return The width of the view, honoring constraints from measureSpec
     */
    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        int length = mText.length();
        int mSplitTextCount = 0;
        if (length<mSplitTextNumber){
            mSplitTextCount = 0;
        }else{
            mSplitTextCount = length / mSplitTextNumber;
            int j = length %mSplitTextNumber;
            if (j!=0){
                mSplitTextCount += 1;
            }
        }

        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else {
            // Measure the text
            result = (int) mPaint.measureText(mText) + getPaddingLeft()+(int)(mSplitTextCount*mGapWidth)
                    + getPaddingRight();
            if (specMode == MeasureSpec.AT_MOST) {
                // Respect AT_MOST value if that was what is called for by measureSpec
                result = Math.min(result, specSize);
            }
        }

        return result;
    }

    /**
     * Determines the height of this view
     * @param measureSpec A measureSpec packed into an int
     * @return The height of the view, honoring constraints from measureSpec
     */
    private int measureHeight(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        float mAscent = (int) mPaint.ascent();
        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else {
            // Measure the text (beware: ascent is a negative number)
            result = (int) (-mAscent + mPaint.descent()) + getPaddingTop()
                    + getPaddingBottom();
            if (specMode == MeasureSpec.AT_MOST) {
                // Respect AT_MOST value if that was what is called for by measureSpec
                result = Math.min(result, specSize);
            }
        }
        return result;
    }


    private void init(Context context, AttributeSet attrs) {
        float defaultTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
        float defaultGapWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics());
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.qr_CitzenCardTextView);
        mText = ta.getString(R.styleable.qr_CitzenCardTextView_qr_text);
        int color = ta.getColor(R.styleable.qr_CitzenCardTextView_qr_text_color,Color.RED);
        float textSize = ta.getDimension(R.styleable.qr_CitzenCardTextView_qr_text_size, defaultTextSize);
        mGapWidth = ta.getDimension(R.styleable.qr_CitzenCardTextView_qr_pertext_margin,defaultGapWidth);
        mSplitTextNumber = ta.getInteger(R.styleable.qr_CitzenCardTextView_qr_split_text_number, 4);
        ta.recycle();



        mPaint = new Paint();
        mPaint.setColor(color);
        mPaint.setTextSize(textSize);
        mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (TextUtils.isEmpty(mText)){
            return;
        }
        Rect rect = new Rect();
        mPaint.getTextBounds(mText, 0, mText.length(), rect);//用一个矩形去"套"字符串,获得能完全套住字符串的最小矩形
        float height = rect.height();//字符串的高度

        int length = mText.length();
        if (length<mSplitTextNumber){
            canvas.drawText(mText,0,height,mPaint);
        }else{
            int count = length / mSplitTextNumber;
            int j = length %mSplitTextNumber;
            List<String> subStrs = new ArrayList<>();
            int i=0;
            while(i<count){
                String substring = mText.substring(i*mSplitTextNumber, i*mSplitTextNumber + mSplitTextNumber);
                i++;
                subStrs.add(substring);
            }
            if (0!=j){
                String substring = mText.substring(i*mSplitTextNumber, length);
                subStrs.add(substring);
            }

            float width = getPaddingLeft();
            int viewWidth = getWidth();
            int index = 0;
            int maxIndex = subStrs.size();
            for (String subStr : subStrs) {
                canvas.drawText(subStr,width,height+10,mPaint);
                Rect subRect = new Rect();
                mPaint.getTextBounds(subStr,0,subStr.length(),subRect);
                width = width + subRect.width(); //mPaint.measureText(subStr);
                width = width + mGapWidth;
                index++;
                int nextWidth = 0;
                if (index < maxIndex){
                    String nextSub = subStrs.get(index);
                    Rect nextsubRect = new Rect();
                    mPaint.getTextBounds(nextSub,0,nextSub.length(),nextsubRect);
                    nextWidth = nextsubRect.width();
                    width = width + nextWidth; //计算时，先将下一个字符宽加进来看
                }
                if (width+getPaddingRight()>viewWidth){
                    height += height+10;
                }
                width = width - nextWidth; //最后再去掉下个段
            }
        }
    }
}
